package com.joshua.spring.aspect;

import com.joshua.spring.constants.MicroServiceHttpHeaders;
import com.joshua.spring.util.IpAddressUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Calendar;


/**
 * projectName dragon-cloud
 * package com.joshua.spring.aspect
 * classname  MicroServiceRespHeaderHandler
 * <p>
 * description
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/8/30 21:52
 */
@Slf4j
@RestControllerAdvice
public class MicroServiceResponseAdvice implements ResponseBodyAdvice<Object> {
    @Value("${spring.application.name:default}")
    private String applicationCode;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        serverHttpResponse.getHeaders().remove(MicroServiceHttpHeaders.X_INNER_SERVICE);
        serverHttpResponse.getHeaders().remove(MicroServiceHttpHeaders.X_CALL_TIME);
        serverHttpResponse.getHeaders().set(MicroServiceHttpHeaders.X_APPLICATION, applicationCode);
        serverHttpResponse.getHeaders().set(MicroServiceHttpHeaders.X_CALL_TIME, Calendar.getInstance().getTime().toString());
        return o;
    }


}
